package com.xxdh.interceptor;

import com.xxdh.util.UserHolder;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //判断此次访问的用户是否登录过
        if(UserHolder.getUserId() == null){
            response.setStatus(401);
            return false;
        }
        return true;
    }

    /**
     * 刷新token过期时间
     * @param request
     * @param response
     * @param handler
     * @param ex
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 创建一个Cookie对象
        Cookie myCookie = new Cookie("userId", UserHolder.getUserId().toString());
        // 设置Cookie的过期时间为1小时（3600秒）
        myCookie.setMaxAge(3600);
        // 设置Cookie的路径（可选）
        myCookie.setPath("/");
        // 将Cookie添加到响应中
        response.addCookie(myCookie);
        // 设置响应内容类型并发送响应（这里只是简单地返回一个消息）
        response.setContentType("application/json");
    }
}
